package com.lunasoft.nettyniodemo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Jierry
 * @version 2016/7/6.
 */
public class TimeClientHandle extends ChannelInboundHandlerAdapter {

    //private final ByteBuf firstMessage;
    private byte[] req;
    private int counter;

    public TimeClientHandle() {
        //req = ("QUERY TIME ORDER"+"\r\n").getBytes();
        req = ("QUERY TIME ORDER"+"$_").getBytes();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf firstMessage;
        for (int i=0;i<100;i++){
            firstMessage = Unpooled.buffer(req.length);
            firstMessage.writeBytes(req);
            ctx.writeAndFlush(firstMessage);//和服务端链路成功后，会调用channelActive，此处发送消息给服务端
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收服务端返回的应答消息
//        ByteBuf buf = (ByteBuf)msg;
//        byte[] req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
//        String body = new String(req,"UTF-8");

        String body = (String)msg;
        System.out.print("Now is:"+body+",this count is:"+ ++counter+"\r\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
